package com.tongqin.distributed.client;


import java.io.*;
import java.net.Socket;

/**
 * @author yuantongqin
 * @date 2018/8/20 下午5:00
 */
public class SocketClient {

    public static void main(String[] args) {
        try {
            Socket socket = new Socket("127.0.0.1",8081);
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write("我现在需要连接你，我带头发送一个消息给你".getBytes());


            InputStream inputStream = socket.getInputStream();
            byte[] bytes = new byte[1024];
            StringBuffer sb = new StringBuffer();
            int len = -1;
            while((len=inputStream.read(bytes))!=0){
                    sb.append(new String(bytes,0,bytes.length));
            }
            System.out.println("来自服务器"+sb.toString());

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭操作
        }
    }

    //默认的端口号
    private static int DEFAULT_SERVER_PORT = 12345;
    private static String DEFAULT_SERVER_IP = "127.0.0.1";
    public static void send(String expression){
        send(DEFAULT_SERVER_PORT,expression);
    }
    public static void send(int port,String expression){
        System.out.println("算术表达式为：" + expression);
        Socket socket = null;
        BufferedReader in = null;
        PrintWriter out = null;
        try{
            socket = new Socket(DEFAULT_SERVER_IP,port);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(),true);
            out.println(expression);
            System.out.println("___结果为：" + in.readLine());
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            //一下必要的清理工作
            if(in != null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                in = null;
            }
            if(out != null){
                out.close();
                out = null;
            }
            if(socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                socket = null;
            }
        }
    }
}
